package com.system.boss.monitor.service;

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.system.boss.monitor.service.dto.JstatGc;
import com.system.boss.monitor.service.dto.TopTask;
import com.system.core.utils.ProcessExecutor;

@Service
public class JstatService {
	
	@Autowired
	private Environment environment;
	private String homedir="/home";

	public JstatGc gc(Integer pid) throws Exception {
		if(pid == null || pid == 0)
			return null;
		String gcstr;
		if(environment.getActiveProfiles()[0].equalsIgnoreCase("dev")) {
			gcstr = " S0C    S1C    S0U    S1U      EC       EU        OC         OU       MC     MU    CCSC   CCSU   YGC     YGCT    FGC    FGCT     GCT   \r\n" + 
					" 0.0   14336.0  0.0   14336.0 230400.0 63488.0   172032.0   127745.0  146504.0 137781.1 17480.0 16035.8     63    1.241   0      0.000    1.241";
		} else {
			gcstr = ProcessExecutor.executeOnce("jstat -gc "+pid,homedir)[1];
		}
		StringReader stringReader = new StringReader(gcstr);
		BufferedReader br = new BufferedReader(stringReader);
		String tmp = null;
		int line = 1;
		ArrayList<TopTask> topTasks = new ArrayList<TopTask>();
		while((tmp = br.readLine()) != null) {
			if(line == 2) {
				JstatGc jstatGc = new JstatGc();
				tmp = tmp.trim();
				String[] gcs = tmp.split("\\s+");
				jstatGc.setS0c(Float.parseFloat(gcs[0]));
				jstatGc.setS1c(Float.parseFloat(gcs[1]));
				jstatGc.setS0u(Float.parseFloat(gcs[2]));
				jstatGc.setS1u(Float.parseFloat(gcs[3]));
				jstatGc.setEc(Float.parseFloat(gcs[4]));
				jstatGc.setEu(Float.parseFloat(gcs[5]));
				jstatGc.setOc(Float.parseFloat(gcs[6]));
				jstatGc.setOu(Float.parseFloat(gcs[7]));
				jstatGc.setMc(Float.parseFloat(gcs[8]));
				jstatGc.setMu(Float.parseFloat(gcs[9]));
				jstatGc.setCcsc(Float.parseFloat(gcs[10]));
				jstatGc.setCcsu(Float.parseFloat(gcs[11]));
				jstatGc.setYgc(Integer.parseInt(gcs[12]));
				jstatGc.setYgct(Float.parseFloat(gcs[13]));
				jstatGc.setFgc(Integer.parseInt(gcs[14]));
				jstatGc.setFgct(Float.parseFloat(gcs[15]));
				jstatGc.setGct(Float.parseFloat(gcs[16]));
				return jstatGc;
			}
			line++;
		}
		return null;
	}
	
	public static void main(String[] args) throws Exception {
		JstatService jstatService = new JstatService();
		System.out.println(jstatService.gc(213));
	}
}
